package com.bytecodezz.app.spline;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;

public class DrawView extends View {
    NativeController nativeController;
    ArrayList<Float> points = new ArrayList<>();
    float dotSize = 10;
    Paint paint;

    public DrawView(Context context) {
        this(context, null);
    }

    public DrawView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        nativeController = new NativeController();
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(dotSize);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                points.clear();
                points.add(event.getX());
                points.add(event.getY());
                invalidate();
                nativeController.nativeDown(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                points.clear();
                long startTime = System.currentTimeMillis();
                float[] dots = nativeController.nativeMove(event.getX(), event.getY());
                long endTime = System.currentTimeMillis();
                Log.e("DrawView", "Time is =" + (endTime - startTime) + "ms    dot size =" + dots.length);
                for (float dot : dots) {
                    points.add(dot);
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                points.add(event.getX());
                points.add(event.getY());
                invalidate();
                nativeController.nativeUp(event.getX(), event.getY());
                break;
        }
        return true;
    }

    public void setParams(float size) {
        nativeController.nativeSetSmooth(size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制dot
        for (int i = 0; i < points.size(); i += 2) {
            canvas.drawPoint(points.get(i), points.get(i + 1), paint);
        }
    }
}
